{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# vrp_resources"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/constraint_solver/vrp_resources.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/ortools/constraint_solver/samples/vrp_resources.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "Vehicles Routing Problem (VRP) with Resource Constraints.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "from ortools.constraint_solver import routing_enums_pb2\n",
    "from ortools.constraint_solver import pywrapcp\n",
    "\n",
    "\n",
    "\n",
    "def create_data_model():\n",
    "    \"\"\"Stores the data for the problem.\"\"\"\n",
    "    data = {}\n",
    "    data[\"time_matrix\"] = [\n",
    "        [0, 6, 9, 8, 7, 3, 6, 2, 3, 2, 6, 6, 4, 4, 5, 9, 7],\n",
    "        [6, 0, 8, 3, 2, 6, 8, 4, 8, 8, 13, 7, 5, 8, 12, 10, 14],\n",
    "        [9, 8, 0, 11, 10, 6, 3, 9, 5, 8, 4, 15, 14, 13, 9, 18, 9],\n",
    "        [8, 3, 11, 0, 1, 7, 10, 6, 10, 10, 14, 6, 7, 9, 14, 6, 16],\n",
    "        [7, 2, 10, 1, 0, 6, 9, 4, 8, 9, 13, 4, 6, 8, 12, 8, 14],\n",
    "        [3, 6, 6, 7, 6, 0, 2, 3, 2, 2, 7, 9, 7, 7, 6, 12, 8],\n",
    "        [6, 8, 3, 10, 9, 2, 0, 6, 2, 5, 4, 12, 10, 10, 6, 15, 5],\n",
    "        [2, 4, 9, 6, 4, 3, 6, 0, 4, 4, 8, 5, 4, 3, 7, 8, 10],\n",
    "        [3, 8, 5, 10, 8, 2, 2, 4, 0, 3, 4, 9, 8, 7, 3, 13, 6],\n",
    "        [2, 8, 8, 10, 9, 2, 5, 4, 3, 0, 4, 6, 5, 4, 3, 9, 5],\n",
    "        [6, 13, 4, 14, 13, 7, 4, 8, 4, 4, 0, 10, 9, 8, 4, 13, 4],\n",
    "        [6, 7, 15, 6, 4, 9, 12, 5, 9, 6, 10, 0, 1, 3, 7, 3, 10],\n",
    "        [4, 5, 14, 7, 6, 7, 10, 4, 8, 5, 9, 1, 0, 2, 6, 4, 8],\n",
    "        [4, 8, 13, 9, 8, 7, 10, 3, 7, 4, 8, 3, 2, 0, 4, 5, 6],\n",
    "        [5, 12, 9, 14, 12, 6, 6, 7, 3, 3, 4, 7, 6, 4, 0, 9, 2],\n",
    "        [9, 10, 18, 6, 8, 12, 15, 8, 13, 9, 13, 3, 4, 5, 9, 0, 9],\n",
    "        [7, 14, 9, 16, 14, 8, 5, 10, 6, 5, 4, 10, 8, 6, 2, 9, 0],\n",
    "    ]\n",
    "    data[\"time_windows\"] = [\n",
    "        (0, 5),  # depot\n",
    "        (7, 12),  # 1\n",
    "        (10, 15),  # 2\n",
    "        (5, 14),  # 3\n",
    "        (5, 13),  # 4\n",
    "        (0, 5),  # 5\n",
    "        (5, 10),  # 6\n",
    "        (0, 10),  # 7\n",
    "        (5, 10),  # 8\n",
    "        (0, 5),  # 9\n",
    "        (10, 16),  # 10\n",
    "        (10, 15),  # 11\n",
    "        (0, 5),  # 12\n",
    "        (5, 10),  # 13\n",
    "        (7, 12),  # 14\n",
    "        (10, 15),  # 15\n",
    "        (5, 15),  # 16\n",
    "    ]\n",
    "    data[\"num_vehicles\"] = 4\n",
    "    data[\"vehicle_load_time\"] = 5\n",
    "    data[\"vehicle_unload_time\"] = 5\n",
    "    data[\"depot_capacity\"] = 2\n",
    "    data[\"depot\"] = 0\n",
    "    return data\n",
    "\n",
    "\n",
    "def print_solution(data, manager, routing, solution):\n",
    "    \"\"\"Prints solution on console.\"\"\"\n",
    "    print(f\"Objective: {solution.ObjectiveValue()}\")\n",
    "    time_dimension = routing.GetDimensionOrDie(\"Time\")\n",
    "    total_time = 0\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        if not routing.IsVehicleUsed(solution, vehicle_id):\n",
    "            continue\n",
    "        index = routing.Start(vehicle_id)\n",
    "        plan_output = f\"Route for vehicle {vehicle_id}:\\n\"\n",
    "        while not routing.IsEnd(index):\n",
    "            time_var = time_dimension.CumulVar(index)\n",
    "            plan_output += (\n",
    "                f\"{manager.IndexToNode(index)}\"\n",
    "                f\" Time({solution.Min(time_var)}, {solution.Max(time_var)})\"\n",
    "                \" -> \"\n",
    "            )\n",
    "            index = solution.Value(routing.NextVar(index))\n",
    "        time_var = time_dimension.CumulVar(index)\n",
    "        plan_output += (\n",
    "            f\"{manager.IndexToNode(index)}\"\n",
    "            f\" Time({solution.Min(time_var)},{solution.Max(time_var)})\\n\"\n",
    "        )\n",
    "        plan_output += f\"Time of the route: {solution.Min(time_var)}min\\n\"\n",
    "        print(plan_output)\n",
    "        total_time += solution.Min(time_var)\n",
    "    print(f\"Total time of all routes: {total_time}min\")\n",
    "\n",
    "\n",
    "def main():\n",
    "    \"\"\"Solve the VRP with time windows.\"\"\"\n",
    "    # Instantiate the data problem.\n",
    "    data = create_data_model()\n",
    "\n",
    "    # Create the routing index manager.\n",
    "    manager = pywrapcp.RoutingIndexManager(\n",
    "        len(data[\"time_matrix\"]), data[\"num_vehicles\"], data[\"depot\"]\n",
    "    )\n",
    "\n",
    "    # Create Routing Model.\n",
    "    routing = pywrapcp.RoutingModel(manager)\n",
    "\n",
    "    # Create and register a transit callback.\n",
    "    def time_callback(from_index, to_index):\n",
    "        \"\"\"Returns the travel time between the two nodes.\"\"\"\n",
    "        # Convert from routing variable Index to time matrix NodeIndex.\n",
    "        from_node = manager.IndexToNode(from_index)\n",
    "        to_node = manager.IndexToNode(to_index)\n",
    "        return data[\"time_matrix\"][from_node][to_node]\n",
    "\n",
    "    transit_callback_index = routing.RegisterTransitCallback(time_callback)\n",
    "\n",
    "    # Define cost of each arc.\n",
    "    routing.SetArcCostEvaluatorOfAllVehicles(transit_callback_index)\n",
    "\n",
    "    # Add Time Windows constraint.\n",
    "    time = \"Time\"\n",
    "    routing.AddDimension(\n",
    "        transit_callback_index,\n",
    "        60,  # allow waiting time\n",
    "        60,  # maximum time per vehicle\n",
    "        False,  # Don't force start cumul to zero.\n",
    "        time,\n",
    "    )\n",
    "    time_dimension = routing.GetDimensionOrDie(time)\n",
    "    # Add time window constraints for each location except depot.\n",
    "    for location_idx, time_window in enumerate(data[\"time_windows\"]):\n",
    "        if location_idx == 0:\n",
    "            continue\n",
    "        index = manager.NodeToIndex(location_idx)\n",
    "        time_dimension.CumulVar(index).SetRange(time_window[0], time_window[1])\n",
    "    # Add time window constraints for each vehicle start node.\n",
    "    for vehicle_id in range(data[\"num_vehicles\"]):\n",
    "        index = routing.Start(vehicle_id)\n",
    "        time_dimension.CumulVar(index).SetRange(\n",
    "            data[\"time_windows\"][0][0], data[\"time_windows\"][0][1]\n",
    "        )\n",
    "\n",
    "    # Add resource constraints at the depot.\n",
    "    solver = routing.solver()\n",
    "    intervals = []\n",
    "    for i in range(data[\"num_vehicles\"]):\n",
    "        # Add time windows at start of routes\n",
    "        intervals.append(\n",
    "            solver.FixedDurationIntervalVar(\n",
    "                time_dimension.CumulVar(routing.Start(i)),\n",
    "                data[\"vehicle_load_time\"],\n",
    "                \"depot_interval\",\n",
    "            )\n",
    "        )\n",
    "        # Add time windows at end of routes.\n",
    "        intervals.append(\n",
    "            solver.FixedDurationIntervalVar(\n",
    "                time_dimension.CumulVar(routing.End(i)),\n",
    "                data[\"vehicle_unload_time\"],\n",
    "                \"depot_interval\",\n",
    "            )\n",
    "        )\n",
    "\n",
    "    depot_usage = [1 for _ in range(len(intervals))]\n",
    "    solver.Add(\n",
    "        solver.Cumulative(intervals, depot_usage, data[\"depot_capacity\"], \"depot\")\n",
    "    )\n",
    "\n",
    "    # Instantiate route start and end times to produce feasible times.\n",
    "    for i in range(data[\"num_vehicles\"]):\n",
    "        routing.AddVariableMinimizedByFinalizer(\n",
    "            time_dimension.CumulVar(routing.Start(i))\n",
    "        )\n",
    "        routing.AddVariableMinimizedByFinalizer(time_dimension.CumulVar(routing.End(i)))\n",
    "\n",
    "    # Setting first solution heuristic.\n",
    "    search_parameters = pywrapcp.DefaultRoutingSearchParameters()\n",
    "    search_parameters.first_solution_strategy = (\n",
    "        routing_enums_pb2.FirstSolutionStrategy.PATH_CHEAPEST_ARC\n",
    "    )\n",
    "\n",
    "    # Solve the problem.\n",
    "    solution = routing.SolveWithParameters(search_parameters)\n",
    "\n",
    "    # Print solution on console.\n",
    "    if solution:\n",
    "        print_solution(data, manager, routing, solution)\n",
    "    else:\n",
    "        print(\"No solution found !\")\n",
    "\n",
    "\n",
    "main()\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
